package com.TeaManage.servlet;

import com.TeaManage.bean.Warehouse;
import com.TeaManage.util.GokJDBCUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "WarehouseServlet", urlPatterns = "/WarehouseServlet")
public class WarehouseServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");
        
        if ("add".equals(action)) {
            // 添加仓库
            String warehouseName = request.getParameter("warehouse_name");
            String location = request.getParameter("location");
            String capacityStr = request.getParameter("capacity");
            String statusStr = request.getParameter("status");
            
            // 验证必填字段
            if (warehouseName == null || warehouseName.trim().isEmpty() ||
                location == null || location.trim().isEmpty()) {
                request.setAttribute("error", "仓库名称和地址不能为空");
                request.getRequestDispatcher("/views/warehouse/addWarehouse.jsp").forward(request, response);
                return;
            }
            
            // 检查仓库名称是否已存在
            String checkSql = "SELECT COUNT(*) FROM warehouse WHERE warehouse_name = ?";
            int count = GokJDBCUtil.queryForCount(checkSql, warehouseName);
            if (count > 0) {
                request.setAttribute("error", "仓库名称已存在");
                request.getRequestDispatcher("/views/warehouse/addWarehouse.jsp").forward(request, response);
                return;
            }
            
            try {
                Double capacity = null;
                if (capacityStr != null && !capacityStr.trim().isEmpty()) {
                    capacity = Double.parseDouble(capacityStr);
                    if (capacity <= 0) {
                        request.setAttribute("error", "仓库容量必须大于0");
                        request.getRequestDispatcher("/views/warehouse/addWarehouse.jsp").forward(request, response);
                        return;
                    }
                }
                
                int status = statusStr != null ? Integer.parseInt(statusStr) : 1;
                
                String sql = "INSERT INTO warehouse(warehouse_name, location, capacity, status) VALUES(?, ?, ?, ?)";
                int result = GokJDBCUtil.update(sql, warehouseName, location, capacity, status);
                if (result > 0) {
                    response.sendRedirect("WarehouseServlet");
                }
                
            } catch (NumberFormatException e) {
                request.setAttribute("error", "容量格式不正确");
                request.getRequestDispatcher("/views/warehouse/addWarehouse.jsp").forward(request, response);
            }
            
        } else if ("toAdd".equals(action)) {
            // 跳转到新增页面
            request.getRequestDispatcher("/views/warehouse/addWarehouse.jsp").forward(request, response);
            
        } else if ("deleteById".equals(action)) {
            // 删除仓库
            int id = Integer.parseInt(request.getParameter("id"));
            
            // 检查是否有库存记录使用此仓库
            String checkSql = "SELECT COUNT(*) FROM tea_inventory WHERE warehouse_id = ?";
            int inventoryCount = GokJDBCUtil.queryForCount(checkSql, id);
            if (inventoryCount > 0) {
                request.setAttribute("error", "该仓库还有库存记录，无法删除");
                loadWarehouseList(request, response);
                return;
            }
            
            String sql = "DELETE FROM warehouse WHERE warehouse_id = ?";
            int result = GokJDBCUtil.update(sql, id);
            response.sendRedirect("WarehouseServlet");
            
        } else if ("findById".equals(action)) {
            // 查找仓库用于编辑
            int id = Integer.parseInt(request.getParameter("id"));
            String sql = "SELECT * FROM warehouse WHERE warehouse_id = ?";
            Warehouse warehouse = GokJDBCUtil.queryForObject(sql, Warehouse.class, id);
            request.setAttribute("warehouse", warehouse);
            request.getRequestDispatcher("/views/warehouse/editWarehouse.jsp").forward(request, response);
            
        } else if ("update".equals(action)) {
            // 更新仓库
            int id = Integer.parseInt(request.getParameter("warehouse_id"));
            String warehouseName = request.getParameter("warehouse_name");
            String location = request.getParameter("location");
            String capacityStr = request.getParameter("capacity");
            String statusStr = request.getParameter("status");
            
            // 验证必填字段
            if (warehouseName == null || warehouseName.trim().isEmpty() ||
                location == null || location.trim().isEmpty()) {
                request.setAttribute("error", "仓库名称和地址不能为空");
                Warehouse warehouse = GokJDBCUtil.queryForObject("SELECT * FROM warehouse WHERE warehouse_id = ?", Warehouse.class, id);
                request.setAttribute("warehouse", warehouse);
                request.getRequestDispatcher("/views/warehouse/editWarehouse.jsp").forward(request, response);
                return;
            }
            
            // 检查仓库名称是否已存在（排除当前仓库）
            String checkSql = "SELECT COUNT(*) FROM warehouse WHERE warehouse_name = ? AND warehouse_id != ?";
            int count = GokJDBCUtil.queryForCount(checkSql, warehouseName, id);
            if (count > 0) {
                request.setAttribute("error", "仓库名称已存在");
                Warehouse warehouse = GokJDBCUtil.queryForObject("SELECT * FROM warehouse WHERE warehouse_id = ?", Warehouse.class, id);
                request.setAttribute("warehouse", warehouse);
                request.getRequestDispatcher("/views/warehouse/editWarehouse.jsp").forward(request, response);
                return;
            }
            
            try {
                Double capacity = null;
                if (capacityStr != null && !capacityStr.trim().isEmpty()) {
                    capacity = Double.parseDouble(capacityStr);
                    if (capacity <= 0) {
                        request.setAttribute("error", "仓库容量必须大于0");
                        Warehouse warehouse = GokJDBCUtil.queryForObject("SELECT * FROM warehouse WHERE warehouse_id = ?", Warehouse.class, id);
                        request.setAttribute("warehouse", warehouse);
                        request.getRequestDispatcher("/views/warehouse/editWarehouse.jsp").forward(request, response);
                        return;
                    }
                }
                
                int status = statusStr != null ? Integer.parseInt(statusStr) : 1;
                
                String sql = "UPDATE warehouse SET warehouse_name = ?, location = ?, capacity = ?, status = ? WHERE warehouse_id = ?";
                int result = GokJDBCUtil.update(sql, warehouseName, location, capacity, status, id);
                if (result > 0) {
                    response.sendRedirect("WarehouseServlet");
                }
                
            } catch (NumberFormatException e) {
                request.setAttribute("error", "容量格式不正确");
                Warehouse warehouse = GokJDBCUtil.queryForObject("SELECT * FROM warehouse WHERE warehouse_id = ?", Warehouse.class, id);
                request.setAttribute("warehouse", warehouse);
                request.getRequestDispatcher("/views/warehouse/editWarehouse.jsp").forward(request, response);
            }
            
        } else if ("search".equals(action)) {
            // 搜索仓库
            String name = request.getParameter("name");
            String location = request.getParameter("location");
            String statusStr = request.getParameter("status");
            
            // 分页参数
            int page = 1;
            int pageSize = 10;
            try {
                page = Integer.parseInt(request.getParameter("page"));
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            } catch (Exception e) {
                page = 1;
                pageSize = 10;
            }
            
            // 构建动态 SQL 和参数列表
            StringBuilder sql = new StringBuilder("SELECT * FROM warehouse WHERE 1=1");
            List<Object> params = new ArrayList<>();
            
            if (name != null && !name.trim().isEmpty()) {
                sql.append(" AND warehouse_name LIKE ?");
                params.add("%" + name + "%");
            }
            if (location != null && !location.trim().isEmpty()) {
                sql.append(" AND location LIKE ?");
                params.add("%" + location + "%");
            }
            if (statusStr != null && !statusStr.trim().isEmpty()) {
                sql.append(" AND status = ?");
                params.add(Integer.parseInt(statusStr));
            }
            
            // 查询总数
            String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") AS total";
            int total = GokJDBCUtil.queryForCount(countSql, params.toArray());
            
            // 添加分页
            sql.append(" ORDER BY warehouse_id DESC LIMIT ?, ?");
            params.add((page - 1) * pageSize);
            params.add(pageSize);
            
            List<Warehouse> warehouseList = GokJDBCUtil.queryAll(sql.toString(), Warehouse.class, params.toArray());
            
            // 计算总页数
            int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            
            // 返回结果
            request.setAttribute("warehouseList", warehouseList);
            request.setAttribute("name", name);
            request.setAttribute("location", location);
            request.setAttribute("status", statusStr);
            request.setAttribute("page", page);
            request.setAttribute("pageSize", pageSize);
            request.setAttribute("totalPages", totalPages);
            request.getRequestDispatcher("views/warehouse/warehouse.jsp").forward(request, response);
            
        } else {
            // 默认显示仓库列表
            loadWarehouseList(request, response);
        }
    }
    
    private void loadWarehouseList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 分页参数
        int page = 1;
        int pageSize = 10;
        try {
            page = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            page = 1;
            pageSize = 10;
        }
        
        // 查询总数
        String countSql = "SELECT COUNT(*) FROM warehouse";
        int total = GokJDBCUtil.queryForCount(countSql);
        
        // 查询数据
        String sql = "SELECT * FROM warehouse ORDER BY warehouse_id DESC LIMIT ?, ?";
        List<Warehouse> warehouseList = GokJDBCUtil.queryAll(sql, Warehouse.class, (page-1)*pageSize, pageSize);
        
        int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        
        request.setAttribute("warehouseList", warehouseList);
        request.setAttribute("page", page);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalPages", totalPages);
        request.getRequestDispatcher("views/warehouse/warehouse.jsp").forward(request, response);
    }
}
